#include "music.h"
#include "audiomanager.h"

using std::string;
using namespace EPOC;

Music::Music(AudioManager *pAudioManager)
{
	m_pAudioManager = pAudioManager;
	SetClassID(kCLASSID_MUSIC);

	m_pMusic = NULL;
	m_bPause = false;
	m_bPlaying = false;
}

Music::~Music()
{
	Music::Cleanup();
}

void Music::Cleanup()
{
	if(m_pMusic)
	{
		Stop();
	
		//Mix_FreeMusic(m_pMusic);
	}

	m_pMusic = NULL;
	
	m_bPlaying = false;
	m_bPause = false;
}

bool Music::Update(float fTimeDelta)
{
	return true;
}

bool Music::Load(string sFilePath)
{
	m_sFilePath = sFilePath;
	
	m_pMusic = m_pAudioManager->LoadMusicFromFile(m_sFilePath);
	if(!m_pMusic)
		return false;

	return true;
}


bool Music::Play(int nTimes)
{
	if(m_bPlaying == true)
		return false;
	
	if(!m_pMusic) 
		return false;
	
	if(nTimes < -1) 
		nTimes = -1;

	if(Mix_PlayMusic(m_pMusic, nTimes) == -1)
		return false;

	m_bPlaying = true;

	//TODO: Count number of times looped

	return true;
}

void Music::Pause()
{
    if(m_bPause == true || m_bPlaying == false) return;
	m_bPause = true;

	Mix_PauseMusic();
}

void Music::Resume()
{
	if(m_bPause == false  || m_bPlaying == false) return;
	m_bPause = false;

	Mix_ResumeMusic();
}

void Music::Stop()
{
	if(m_bPlaying == false) return;
	m_bPlaying = false;
	m_bPause = false;

	Mix_HaltMusic();
}

void Music::Rewind()
{
	Mix_RewindMusic();
}

void Music::SetVolume(int nVolume)
{
	if(nVolume < 0) nVolume = 0;
	else if(nVolume > 100) nVolume = 100;
	
	float fRatio = (float)nVolume / (float)100;

	m_nVolume = (int)(fRatio * (float)MIX_MAX_VOLUME + 0.5f);

	Mix_VolumeMusic(m_nVolume);
}

int Music::GetVolume()
{
	float fRatio = (float)m_nVolume / (float)MIX_MAX_VOLUME;
	int nVolume = (int)(100.0f * fRatio + 0.5f);

	return nVolume;
}